#!/usr/bin/env bash
start=$(date +%s) 
############################
# 自定义参数
############################
project_name="YXKitOC"
project_chinese_name="YXKitOC"
scheme_name="YXKitOC"
archiive_mode="Release"
plist_name="options_enterprise_dis"
image_name="pods.png"
info_plist_name="YXKitOC/Info.plist"
show_log="yes"
############################
# 自定义参数
############################

project_path=$(
	cd $(dirname $0)
	cd ..
	pwd
)
cd $project_path
echo 当前路径

sha=$CI_COMMIT_SHA
commit=$(git log -1 --format="%s" $sha)

echo '' 
echo sha=$sha
echo commit=$commit
echo ''

branch_name=$CI_COMMIT_REF_NAME
auto_archive=$1

# 自动打包不显示打包log
# if [ ${auto_archive}x = "autox" ]; then
# 	show_log="no"
# fi

# 切换分支
# 参数1 切换的分支名称
if [ ${auto_archive}x = "autox" ]; then
	sh 1_AutoArchive/1_changeBranch.sh $branch_name || exit
fi

# 更新iOS代码
sh 1_AutoArchive/1_updateGit.sh $auto_archive || exit
 
# 自动打包时，提交记录有-qa; -release打包，否则不打包;
if [ ${auto_archive}x = "autox" ]; then
	sha=$CI_COMMIT_SHA
	commit=$(git log -1 --format="%s" $sha)

	echo ''
	echo sha=$sha
	echo commit=$commit
	echo ''

	mode_qa='-qa;'
	mode_release='-release;'
	if [[ $commit =~ ^$mode_qa* ]]; then
		echo "正在打测试包Debug"
	elif [[ $commit =~ ^$mode_release* ]]; then
		echo "正在打线上包Release"
	else
		echo '未识别到打包命令'
		exit 0
	fi
fi

# 版本号
version=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" $info_plist_name)
# build号
build=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" $info_plist_name)

# branchName
branch_name=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')

echo "\033[31m ###################################### \033[0m"
echo "\033[31m ###################################### \033[0m"
echo
echo "\033[31m 正在打包$project_chinese_name 分支：$branch_name 版本号：${version}_${build} \033[0m"
echo
echo "\033[31m ###################################### \033[0m"
echo "\033[31m ###################################### \033[0m"

# 打包并导出ipa
# 参数1：项目名称 参数2：scheme名称 参数3：打包模式 Debug/Release/Enterprise
# 参数4：plist文件名称
sh 1_AutoArchive/3_archive.sh $project_name $scheme_name $archiive_mode $plist_name $show_log || exit
pwd

# 上传ipa至远程服务器
# 参数1：项目名称
sh 1_AutoArchive/4_upload_ipa.sh $project_name || exit

# 更新远程html
# 参数1：项目名称 参数2：中文名称 参数3：远程服务器图片名称
sh 1_AutoArchive/5_updateHTML.sh $project_name $project_chinese_name "" $image_name $version $build || exit

end=$(date +%s)
end_string=$((( $end - $start ) / 60 ))分钟
echo "\033[31m ${end_string} \033[0m"
